package cn.wjh.business.utils;

import cn.wjh.business.config.BusinessConfig;
import com.ruoyi.common.utils.spring.SpringUtils;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Arrays;

@Component
public class IpAddressParser {
    //ip搜索
    private static  Searcher searcher;

	@PostConstruct
	public void init() {
		BusinessConfig config = SpringUtils.getBean(BusinessConfig.class);
		//初始化searcher
		String path = config.getIp2regionDbPath();
		try {
			byte[] vIndex = Searcher.loadVectorIndexFromFile(path);
			searcher = Searcher.newWithVectorIndex(path, vIndex);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

    public static String parse(String ip) {
        String search = null;
        try {
            search = searcher.search(ip);
            String[] addrs = search.split("\\|");
            String province = addrs[2]; //获取省份
            province = province.replaceAll("省", "");
            search = province.equals("0") ? "内网" : province;
        } catch (Exception e) {
            search = "未知";
        }
        return search;
    }
}
